#include <cmath>
#include <iostream>
#include "vertex.h"

using namespace std;

bool operator==(Vertex v1, Vertex v2){
	return ((v1.x == v2.x) && (v1.y == v2.y) && (v1.y == v2.y));
}

float dist(Vertex v1, Vertex v2){
		return sqrt((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + (v1.z - v2.z)*(v1.z - v2.z)); 
}

float Vertex::length(){ 
		return sqrt(x*x + y*y + z*z); 
}

float dot_product(Vertex v1, Vertex v2){
	return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

Vertex project_point(Vertex v, Line l){
	Line l1(-l.b, l.a, l.b*v.x - l.a*v.y);
	Vertex r = lines_intersection(l, l1);
	return r;
}

bool parallel(Line l1, Line l2){
	float t = l1.a*l2.b - l2.a*l1.b;
	if ((t <= 0.002) && (t >= -0.002))
		return true;
	return false;
}

Vertex lines_intersection(Line l1, Line l2){
	Vertex r;
	r.x = -(l1.c*l2.b - l2.c*l1.b)/(l1.a*l2.b - l2.a*l1.b);
	r.y = -(l1.a*l2.c - l2.a*l1.c)/(l1.a*l2.b - l2.a*l1.b);
	r.z = 0;
	return r;
}

Vertex diff(Vertex v1, Vertex v2){
		Vertex n;
		n.x = v2.x - v1.x;
		n.y = v2.y - v1.y;
		n.z = v2.z - v1.z;
		return n;
}

istream & operator >> (istream& is, Vertex & v){
	is >> v.x;
	is >> v.y;
	is >> v.z;
	return is;
}

Vertex::Vertex():x(0), y(0), z(0){}

Line::Line(float x1, float y1, float x2, float y2){
	a = y2 - y1;
	b = x1 - x2;
	c = -x1*(y2 - y1) + y1*(x2 - x1);
}

bool point_on_lineseg(Vertex v, Vertex v1, Vertex v2){
	if (!point_on_line(v, v1, v2))
		return false;
	if (v1.x == v2.x){
		if (((v.y <= v1.y) && (v.y >= v2.y)) || ((v.y >= v1.y) && (v.y <= v2.y)))
			return true;
	}
	else if (((v.x <= v1.x) && (v.x >= v2.x)) || ((v.x >= v1.x) && (v.x <= v2.x)))
		return true;
	return false;
}

bool point_on_line(Vertex v, Vertex v1, Vertex v2){
	Line l(v1.x, v1.y, v2.x, v2.y);
	float t = l.a*v.x + l.b*v.y + l.c;
	if ((t <= 0.002) && (t >= -0.002))
		return true;
	return false;
}